#!/usr/bin/python

#    tribalgrowth is a growth monitor for the online game Tribal Wars.
#    Copyright 2009 Nathan Michaels                                            
#                                                                              
#    This file is part of tribalgrowth.                                        
#                                                                              
#    tribalgrowth is free software: you can redistribute it and/or modify      
#    it under the terms of the GNU General Public License as published by      
#    the Free Software Foundation, either version 2 of the License, or         
#    (at your option) any later version.                                       
#                                                                              
#    tribalgrowth is distributed in the hope that it will be useful,           
#    but WITHOUT ANY WARRANTY; without even the implied warranty of            
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the             
#    GNU General Public License for more details.                              
#                                                                              
#    You should have received a copy of the GNU General Public License         
#    along with tribalgrowth.  If not, see <http://www.gnu.org/licenses/>. 

import time
from timer import timeonce
import database, grabber, deltinator

fileName = 'tribal.db' # This is the name of the database file to be used.

def test ():
    print '*'*20
    print "Wake up at",time.time()
    grabTime, t = timeonce (grabber.grab)
    now = int (time.time())
    print 'Grab:', grabTime
    parseTime, villages = timeonce (grabber.dictify, t)
    print 'Parse:', parseTime
    createDBTime, db = timeonce (database.TribalDB, fileName)
    print 'Creation:', createDBTime
    addVillagesTime, ignore = timeonce (db.AddVillages, now, villages)
    print 'Add Villages:', addVillagesTime
    deltaTime, ignore = timeonce (IncrementDeltas)
    print 'Calculate Deltas:', deltaTime
    return db

def GetNewData ():
    villages = grabber.get_dict ()
    now = int (time.time())
    db = database.TribalDB (fileName)
    db.AddVillages (now, villages)
    return db

def CreateDeltas ():
    base = deltinator.DeltaDB (fileName)
    base.UpdateAll ()
    return base

def IncrementDeltas ():
    base = deltinator.DeltaDB (fileName)
    base.QuickUpdate ()
    return base

def Periodic (interval):
    """Grab a new file and assimilate it every [interval] seconds. This
    function should not drift more than the host system's clock."""

    now = time.time()
    last = now - interval
    while True:
        now = time.time()
        if now >= last + interval:
            test ();
            last = last + interval
        else:
            # Xeno's nap!
            time.sleep (int ((last + interval - now) / 2.0))

if __name__=='__main__':
    Periodic (3600)
